﻿using System.Security.Principal;
using System.ServiceModel;

namespace SharePointUtilitiesForDevelopers.Service
{
    /// <summary>
    /// Creates instances of SharePoint services.
    /// </summary>
    internal static class SharePointServiceClientFactory
    {
        /// <summary>
        /// Creates a soap client instance.
        /// </summary>
        /// <typeparam name="TSoapClient">The type of the SOAP client.</typeparam>
        /// <typeparam name="TChannel">The type of the channel.</typeparam>
        /// <param name="siteUrl">The site URL.</param>
        /// <returns>A soap client instance.</returns>
        internal static TSoapClient CreateInstance<TSoapClient, TChannel>(string siteUrl)
            where TSoapClient: ClientBase<TChannel>
            where TChannel: class
        {
            // Create the proxy
            var client = ServiceLocator.Resolve<ISharePointServiceClientFactory<TSoapClient, TChannel>>().CreateInstance(siteUrl);

            // Set the credentials
            client.ClientCredentials.Windows.ClientCredential = SharePointServiceCredentialCache.GetCredential(siteUrl);

            // Set the client to impersonate the caller
            client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
            
            return client;
        }
    }
}